package at.fhj.itm10.ticketmaster.validators;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.validator.FacesValidator;
import javax.faces.validator.Validator;
import javax.faces.validator.ValidatorException;

import at.fhj.itm10.ticketmaster.entities.Customer;
import at.fhj.itm10.ticketmaster.services.ServiceException;
import at.fhj.itm10.ticketmaster.services.ServiceFactory;

/**
 * prüft unique email
 * @author Ballach
 *
 */
@FacesValidator(value="UniqueEMailValidator")
public class UniqueEMailValidator implements Validator{
	
	
	public void validate(FacesContext facesContext, UIComponent uIComponent,
			Object object) {

		/*ServiceBean serviceBean = (ServiceBean) facesContext.getApplication()
				.evaluateExpressionGet(
				facesContext, "#{service}", ServiceBean.class);*/
		
		String enteredEmail = (String) object;
		boolean alreadyExists = false;
		

			ServiceFactory factory = new ServiceFactory();
			Customer listEMail = factory.getCustomerService()
					.findByEMail(enteredEmail);
			if (listEMail != null) {
				alreadyExists = true;
			}


		if(alreadyExists == true) {

			String text = null;
			text = "Diese E-Mail existiert bereits. Bitte geben Sie eine andere ein.";

			FacesMessage message = new FacesMessage();
			message.setDetail(text);

			message.setSeverity(FacesMessage.SEVERITY_ERROR);
			throw new ValidatorException(message);
		}
	}
}
